package com.service;

import com.bugs.factory.SpiderFactory;
import com.dao.WorkBugRepository;
import com.model.WorkBug;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class WorkBugService {

    @Autowired
    private WorkBugRepository workBugRepository;


    public void save(WorkBug workBug) {
        workBugRepository.save(workBug);
    }

    public List<WorkBug> findAll() {
        List<WorkBug> bugs = workBugRepository.findAll();
        bugs.forEach(bug -> {
            bug.setActioning(SpiderFactory.workIsActioning(bug));
            bug.setActionTime(SpiderFactory.workStartTime(bug));
            bug.setSaveDbCount(SpiderFactory.getSaveDbCount(bug));
        });
        return bugs;
    }

    public void update(WorkBug workBug) {
        workBugRepository.saveAndFlush(workBug);
    }

    public void deleteById(long id) {
        WorkBug workBug = workBugRepository.findById(id).get();
        workBugRepository.deleteById(id);
        SpiderFactory.closeSpider(workBug);
    }

    public void actionById(long id) {
        WorkBug workBug = workBugRepository.findById(id).get();
        SpiderFactory.actionSpider(workBug);

    }

    public void suspendById(Long id) {
        WorkBug workBug = workBugRepository.findById(id).get();
        SpiderFactory.suspendSpider(workBug);
    }

    public WorkBug getById(Long id) {
        return workBugRepository.findById(id).get();
    }
}
